// 获取DOM元素
const codeEditor = document.getElementById('codeEditor');
const output = document.getElementById('output');
const runBtn = document.getElementById('runBtn');
const resetBtn = document.getElementById('resetBtn');

// 加载默认代码
async function loadDefaultCode() {
    try {
        const response = await fetch('/api/default-code');
        const data = await response.json();
        codeEditor.value = data.code;
    } catch (error) {
        console.error('加载默认代码失败:', error);
        codeEditor.value = `#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World";
    return 0;
}`;
    }
}

// 运行代码
async function runCode() {
    const code = codeEditor.value.trim();
    
    if (!code) {
        showOutput('错误：代码不能为空', 'error');
        return;
    }

    // 禁用运行按钮，显示加载状态
    runBtn.disabled = true;
    runBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>运行中...';
    showOutput('正在编译和运行代码...', 'info');

    try {
        const response = await fetch('/api/run', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ code })
        });

        const result = await response.json();
        
        if (result.success) {
            showOutput(result.output, 'success');
        } else {
            showOutput(`编译错误：\n${result.error}`, 'error');
        }
    } catch (error) {
        showOutput(`网络错误：${error.message}`, 'error');
    } finally {
        // 恢复运行按钮
        runBtn.disabled = false;
        runBtn.innerHTML = '<i class="fas fa-play mr-1"></i>运行';
    }
}

// 显示输出
function showOutput(text, type = 'info') {
    let colorClass = '';
    switch (type) {
        case 'success':
            colorClass = 'text-green-400';
            break;
        case 'error':
            colorClass = 'text-red-400';
            break;
        case 'info':
            colorClass = 'text-blue-400';
            break;
        default:
            colorClass = 'text-gray-400';
    }

    output.innerHTML = `<div class="${colorClass} whitespace-pre-wrap">${text}</div>`;
}

// 重置代码
function resetCode() {
    loadDefaultCode();
    showOutput('代码已重置为默认值', 'info');
}

// 事件监听
runBtn.addEventListener('click', runCode);
resetBtn.addEventListener('click', resetCode);
codeEditor.addEventListener('keydown', (e) => {
    // 支持Ctrl+Enter快捷键运行
    if (e.ctrlKey && e.key === 'Enter') {
        e.preventDefault();
        runCode();
    }
});

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    loadDefaultCode();
});
